namespace C4F.DevKit.Contacts
{
    using C4F.DevKit.Contacts.Standard;
    using System;
    using System.IO;
    using System.Windows.Controls;
    using System.Windows.Media.Imaging;
    using C4F.DevKit.Contacts.Interop;
    using System.Windows.Interop;
    using System.Windows;
    using System.Text;

    /// <summary>
    /// Utilities for rendering a Contact's User Tile image in different ways.
    /// </summary>
    public class UserTile
    {
        private BitmapSource _image;

        internal UserTile(Contact contact)
        {
            _image = _GetFramedPhoto(contact, 96);
        }

        /// <summary>
        /// The image associated with the user tile.
        /// </summary>
        public BitmapSource Image
        {
            get
            {
                return _image;
            }
        }

        private static BitmapSource _GetFramedPhoto(Contact contact, int dimensions)
        {
            ContactShellExtensionHandlerRcw thumbnailProvider = null;
            try
            {
                using (MemoryStream memstream = new MemoryStream())
                {
                    contact.Save(memstream);
                    memstream.Position = 0;
                    using (ManagedIStream pstm = new ManagedIStream(memstream))
                    {
                        thumbnailProvider = new ContactShellExtensionHandlerRcw();
                        thumbnailProvider.Load(pstm).ThrowIfFailed();

                        IntPtr hBitmap = IntPtr.Zero;
                        StringBuilder sb = new StringBuilder(256);
                        int dwPriority = 0;
                        int dwFlags = 0;
                        SIZE rgSize = new SIZE(dimensions, dimensions);
                        thumbnailProvider.GetLocation(sb, sb.Capacity, ref dwPriority, ref rgSize, 32, ref dwFlags);

                        try
                        {
                            thumbnailProvider.Extract(out hBitmap);

                            return Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                        }
                        finally
                        {
                            Utility.SafeDeleteObject(ref hBitmap);
                        }
                    }
                }
            }
            finally
            {
                Utility.SafeRelease(ref thumbnailProvider);
            }
        }

        public static BitmapSource GetFramedPhoto(Photo photo, int dimensions)
        {
            using (Contact contact = new Contact())
            {
                contact.Photos[PhotoLabels.UserTile] = photo;
                return _GetFramedPhoto(contact, dimensions);
            }
        }
    }
}
